<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { EtlInstanceVO, EtlProgress } from '@/service/api/dataplatform/etl';
import { getEtlInstanceList, getEtlProgress, stopEtlTask } from '@/service/api/dataplatform/etl';
import { ElMessage, ElMessageBox } from 'element-plus';

const visible = ref(false);
const loading = ref(false);
const tableData = ref<EtlInstanceVO[]>([]);
const total = ref(0);
const taskId = ref<number>();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskId: undefined as number | undefined
});

const progressDialogVisible = ref(false);
const currentProgress = ref<EtlProgress>();
const progressTimer = ref<number>();

/** 打开抽屉 */
function open(id: number) {
  taskId.value = id;
  queryParams.taskId = id;
  visible.value = true;
  getList();
}

/** 查询列表 */
async function getList() {
  loading.value = true;
  try {
    const { data } = await getEtlInstanceList(queryParams);
    tableData.value = data.rows;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
}

/** 查看进度 */
async function handleViewProgress(row: EtlInstanceVO) {
  progressDialogVisible.value = true;
  currentProgress.value = undefined;

  // 开始轮询进度
  startProgressPolling(row.id);
}

/** 开始轮询进度 */
function startProgressPolling(instanceId: number) {
  // 清除之前的定时器
  if (progressTimer.value) {
    clearInterval(progressTimer.value);
  }

  // 立即获取一次
  fetchProgress(instanceId);

  // 每2秒轮询一次
  progressTimer.value = window.setInterval(() => {
    fetchProgress(instanceId);
  }, 2000);
}

/** 获取进度 */
async function fetchProgress(instanceId: number) {
  try {
    const { data } = await getEtlProgress(instanceId);
    currentProgress.value = data;

    // 如果任务已完成，停止轮询
    if (data.status === 'SUCCESS' || data.status === 'FAILED' || data.status === 'STOPPED') {
      stopProgressPolling();
      // 刷新列表
      getList();
    }
  } catch (error) {
    console.error('获取进度失败', error);
  }
}

/** 停止轮询 */
function stopProgressPolling() {
  if (progressTimer.value) {
    clearInterval(progressTimer.value);
    progressTimer.value = undefined;
  }
}

/** 停止任务 */
async function handleStop(row: EtlInstanceVO) {
  try {
    await ElMessageBox.confirm('确认停止该任务吗？', '提示', {
      type: 'warning'
    });
    await stopEtlTask(row.id);
    ElMessage.success('停止成功');
    getList();
  } catch (error) {
    // 用户取消
  }
}

/** 查看日志 */
function handleViewLogs(row: EtlInstanceVO) {
  ElMessageBox.alert(row.logs || '暂无日志', '执行日志', {
    confirmButtonText: '关闭',
    customClass: 'log-message-box'
  });
}

/** 获取状态标签类型 */
function getStatusTag(status: string) {
  const map: Record<string, any> = {
    RUNNING: 'primary',
    SUCCESS: 'success',
    FAILED: 'danger',
    STOPPED: 'info'
  };
  return map[status] || 'info';
}

/** 获取状态文本 */
function getStatusText(status: string) {
  const map: Record<string, string> = {
    RUNNING: '运行中',
    SUCCESS: '成功',
    FAILED: '失败',
    STOPPED: '已停止'
  };
  return map[status] || status;
}

/** 格式化时长 */
function formatDuration(ms?: number) {
  if (!ms) return '-';
  const seconds = Math.floor(ms / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  if (hours > 0) {
    return `${hours}小时${minutes % 60}分${seconds % 60}秒`;
  } else if (minutes > 0) {
    return `${minutes}分${seconds % 60}秒`;
  } else {
    return `${seconds}秒`;
  }
}

/** 关闭进度对话框 */
function handleCloseProgress() {
  progressDialogVisible.value = false;
  stopProgressPolling();
}

/** 关闭抽屉 */
function handleClose() {
  visible.value = false;
  stopProgressPolling();
}

defineExpose({
  open
});
</script>

<template>
  <el-drawer
    v-model="visible"
    title="任务实例列表"
    size="80%"
    @close="handleClose"
  >
    <el-table v-loading="loading" :data="tableData" border>
      <el-table-column prop="id" label="实例ID" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope && scope.row" :type="getStatusTag(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="160" />
      <el-table-column prop="endTime" label="结束时间" width="160" />
      <el-table-column prop="duration" label="执行时长" width="120">
        <template #default="scope">
          {{ scope && scope.row ? formatDuration(scope.row.duration) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="sourceRows" label="源行数" width="100" />
      <el-table-column prop="targetRows" label="目标行数" width="100" />
      <el-table-column prop="successRows" label="成功行数" width="100" />
      <el-table-column prop="failedRows" label="失败行数" width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <template v-if="scope && scope.row">
            <el-button
              v-if="scope.row.status === 'RUNNING'"
              link
              type="primary"
              @click="handleViewProgress(scope.row)"
            >
              <icon-ic-round-visibility class="mr-4px" />
              进度
            </el-button>
            <el-button
              v-if="scope.row.status === 'RUNNING'"
              link
              type="danger"
              @click="handleStop(scope.row)"
            >
              <icon-ic-round-stop class="mr-4px" />
              停止
            </el-button>
            <el-button link type="primary" @click="handleViewLogs(scope.row)">
              <icon-ic-round-description class="mr-4px" />
              日志
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="mt-4"
      @size-change="getList"
      @current-change="getList"
    />

    <!-- 进度对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="执行进度"
      width="500px"
      @close="handleCloseProgress"
    >
      <div v-if="currentProgress" class="progress-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentProgress.status)">
              {{ getStatusText(currentProgress.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前步骤">
            {{ currentProgress.currentStep }}
          </el-descriptions-item>
          <el-descriptions-item label="进度">
            <el-progress :percentage="currentProgress.percentage" />
          </el-descriptions-item>
          <el-descriptions-item label="已处理行数">
            {{ currentProgress.processedRows || 0 }} / {{ currentProgress.totalRows || 0 }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentProgress.errorMessage" label="错误信息">
            <el-text type="danger">{{ currentProgress.errorMessage }}</el-text>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="text-center py-4">
        <el-icon class="is-loading" :size="32">
          <icon-ic-round-refresh />
        </el-icon>
        <div class="mt-2">加载中...</div>
      </div>
    </el-dialog>
  </el-drawer>
</template>

<style scoped>
.progress-content {
  padding: 20px 0;
}

:deep(.log-message-box) {
  width: 600px;
}

:deep(.log-message-box .el-message-box__message) {
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  font-family: monospace;
  font-size: 12px;
}
</style>
